//删除的id
var delId = [];
var oprateUrl = DOMAIN + '/v1/ticket' + isLogin;
function loadTable() {
	$("#table").bootstrapTable({ // 对应table标签的id
		url: oprateUrl,
		method: 'get',
		cache: false,
		striped: true,
		pagination: true,
		pageSize: 5,
		pageNumber: 1,
		pageList: [5, 10],
		search: false,
		showColumns: false,
		clickToSelect: true,
		queryParams: {
			deleteFlg: 0
		},
		smartDisplay: false,
		columns: [{
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}, {
			field: "ticketNo",
			title: "申请单号",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "ticketDate",
			title: "申请日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "proposer",
			title: "申请人",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "sumMoney",
			title: "总金额",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "comments",
			title: "备注",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "ticketStatus",
			title: "开票申请状态",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function (value, row, index) {
				if (row.ticketStatus != "开启") {
					return '<button ticketNo="' + row.ticketNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="CheckInfo(this)" class="btn btn-primary btn-sm edit">&emsp;查看</button>';
				} else {
					return '<button ticketNo="' + row.ticketNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">&emsp;编辑</button> <button ticketNo="' + row.ticketNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="AuditInfo(this)" class="btn btn-primary btn-sm edit">&emsp;操作</button>';
				}
			}
		}],
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		showExport: true,
		//是否显示导出按钮
		buttonsAlign: "left",
		//按钮位置
		exportDataType: 'all',
		//导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		Icons: 'glyphicon glyphicon-export',
		exportTypes: ['excel', 'doc', 'xlsx', 'txt',],
		//导出文件类型
		exportOptions: {
			ignoreColumn: [0, 0],  //忽略某一列的索引，id删除更新用用，不显示与导出

			fileName: '导出数据表',
			//文件名称设置
			worksheetName: 'sheet1',
			//表格工作区名称
			tableName: '导出数据表',
			// excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式

		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
		formatNoMatches: function () {
			return '没有找到匹配的记录';
		}
	});
	function queryParams(params) {
		var params = {};
		return params;
	};
}

//查询
$("#selectPurchaseBtn").click(function () {
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.beginDate = $("#beginDate").val();
		params.endDate = $("#endDate").val();
		params.ticketNo = $("#ticketNo").val();
		params.ticketStatus = $("#ticketStatus option:checked").val();
		return params;
	};
	var url = DOMAIN + '/v1/ticket' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

$("#tableAddDetail").bootstrapTable({ // 对应table标签的id
	url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 5,
	pageNumber: 1,
	pageList: [5, 10],
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "ticketNo",
		title: "申请单号",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productLevelOne",
		title: "产品一级类型",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "productLevelTwo",
		title: "产品二级类型",
		align: "center",
		valign: "middle",
		sortable: "true",
		formatter: function (value, row, index) {
                return row.productLevelTwo==""?"-":row.productLevelOne;
            }
	}, {
		field: "productName",
		title: "产品名称",
		align: "center",
		valign: "middle",
		sortable: "true",
		formatter: function (value, row, index) {
                return row.productName==""?"-":row.productName;
            }
	}, {
		field: "money",
		title: "金额",
		align: "center",
		valign: "middle",
		sortable: "true"
	}],
	formatNoMatches: function () {
		return '';
	}
	//保存的使用
});
function queryParams(params) {
	return params;
};

//新增按钮，不存到数据库
$("#AddPur-insertBtn").click(function () {

	//获取数据
	var productLevelOne = $('#productLevelOne').val();
	var productLevelTwo = $('#productLevelTwo').val();
	var productName = $('#productName').val();
	var money = $('#money').val();
	
	var count = $('#tableAddDetail').bootstrapTable('getData').length;
	var options = $("#tableAddDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	var t = getFormJsonObject($("#info"));
	var flag = false;
	var flag = isInfoNull(t);
	if (!flag) {
		return;
	}
	$('#tableAddDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			pid: pid,
			productName: productName,
			productLevelOne: productLevelOne,
			productLevelTwo: productLevelTwo,
			money: money
		}
	});
	//新增后置空
	$('#productLevelOne').val('');
	$('#productLevelTwo').val('');
	$('#productName').val('');
	$('#money').val('');
});


//保存
$("#AddPur-saveBtn").click(function () {
	//得到新增表格数据
	var params = getDataForAdd();
	var flag = false;
	var flag = isMainNull(params);;
	if (!flag) {
		//alert("请先输入数据");
		return;
	}
	params = JSON.stringify(params);
	//进货id是否绑定,没有id就新增
	var mainId = $('#mainId').val();
	if (mainId == '' || mainId == null) {
		$.ajax({
			type: "post",
			url: DOMAIN + '/v1/ticket' + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('保存失败');
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#mainId').val('');
		$('.close').click();
	} else {
		//更新
		$.ajax({
			type: "patch",
			url: DOMAIN + '/v1/ticket/' + mainId + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('编辑失败');
			},
			complete: function () {
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#mainId').val('');
		$('.close').click();
		//将删除的id置空
		delId = [];
	}
});

//新增时获取数据的方法
function getDataForAdd() {
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var params = {};
	params.ticketDate = $("#ticketDate").val();
	params.proposer = $("#proposer").val();
	params.sumMoney = $("#sumMoney").val();
	params.comments = $("#comments").val();
	params.ticketNo = $('#ticketNoAdd').val();
	params.ticketInfoList = rows;
	params.delId = delId;
	return params;

}

//删除选中行
$("#AddPur-deleteBtn").click(function () {
	var ids = $("#tableAddDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'id', values: [id] });
				delId.push(id);
				}
		}

	}
});


function isMainNull(t) {

	if (t.ticketDate == '' || t.ticketDate == null) {
		alert("申请日期不能为空");
		return false;
	}
	if (t.proposer == '' || t.proposer == null) {
		alert("申请人不能为空");
		return false;
	}
	if (t.sumMoney == '' || t.sumMoney == null) {
		alert("总金额不能为空");
		return false;
	}
	return true;
}
function isInfoNull(t) {

	if (t.productLevelOne == '' || t.productLevelOne == null) {
		alert("产品一级类型不能为空");
		return false;
	}
	if (t.money == '' || t.money <= 0) {
		alert("金额必须大于零");
		return false;
	}
	return true;
}

//编辑信息
function EditInfo(e) {
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#info').css("display","block");
	$('#info-btn').css("display","block");
	$("#Audit-btn").css("display","none");
	$("#main1 input").removeAttr("readonly");
	$("#main1 input").css("background-color","");
	$('#info')[0].reset();
	//将删除的id置空
	delId = [];
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var ticketNo = $(e).attr('ticketNo');
	var url = DOMAIN + '/v1/ticketInfo' + isLogin + '&ticketNo=' + ticketNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
}

//查看信息
function CheckInfo(e){
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#info')[0].reset();
	//将删除的id置空
	delId = [];
	$('#info').css("display","none");
	$('#info-btn').css("display","none");
	$("#Audit-btn").css("display","none");
	$("#main1 input").attr("readonly","readonly");
	$("#main1 input").css("background-color","#ccc");
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var ticketNo = $(e).attr('ticketNo');
	var url = DOMAIN + '/v1/ticketInfo' + isLogin + '&ticketNo=' + ticketNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
}

//操作按钮
function AuditInfo(e){
	$('#info').css("display","none");
	$('#info-btn').css("display","none");
	$("#Audit-btn").css("display","block");
	$("#main1 input").attr("readonly","readonly");
	$("#main1 input").css("background-color","#ccc");
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#info')[0].reset();
	//将删除的id置空
	delId = [];
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var ticketNo = $(e).attr('ticketNo');
	var url = DOMAIN + '/v1/ticketInfo' + isLogin + '&ticketNo=' + ticketNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
}

//新增前填写日期并获取批次号与进货编号
function resetTable() {
	//将删除的id置空
	delId = [];
	$('#main1')[0].reset();
	$('#info')[0].reset();

	$('#tableAddDetail').bootstrapTable('removeAll');
}

function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function (n, i) {
		indexed_array[n['name']] = n['value'];
	});

	return indexed_array;
};

//下拉框填充
$(function () {
	//	时间初试化
	$('#ticketDate').datetimepicker({
		minView: "month",
		language: 'zh-CN',
		format: 'yyyy-mm-dd',
		todayBtn: 1,
		autoclose: true
	});
	$('#beginDate').datetimepicker({
		minView: "month",
		language: 'zh-CN',
		format: 'yyyy-mm-dd',
		todayBtn: 1,
		autoclose: true
	});
	$('#endDate').datetimepicker({
		minView: "month",
		language: 'zh-CN',
		format: 'yyyy-mm-dd',
		todayBtn: 1,
		autoclose: true
	});
	
	time_rota($("#ticketDate"));
	time_rota2($("#beginDate"));
	time_rota($("#endDate"));
	loadTable();
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.beginDate = $("#beginDate").val();
		params.endDate = $("#endDate").val();
		params.ticketNo = $("#ticketNo").val();
		params.ticketStatus = $("#ticketStatus option:checked").val();
		return params;
	};
	var url = DOMAIN + '/v1/ticket' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	
	$("#insert-purBtn").on("click",function(){
		$('#mainId').val(""); 
		$('#info').css("display","block");
		$("#Audit-btn").css("display","none");
		$('#info-btn').css("display","block");
		$("#main1 input").removeAttr("readonly");
		$("#main1 input").css("background-color","");
	});
})

$("#Audit-sure").click(function(){
	var rf = confirm("确定提交此申请吗？(提交后不可修改)");
	if(rf){
		var params = {};
		params.ticketDate = $("#ticketDate").val();
		params.proposer = $("#proposer").val();
		params.sumMoney = $("#sumMoney").val();
		params.comments = $("#comments").val();
		params.ticketStatus = "审核中";
		params = JSON.stringify(params);
		var mainId = $("#mainId").val();
		$.ajax({
				type: "patch",
				url: DOMAIN + '/v1/ticket/' + mainId + isLogin,
				data: params,
				dataType: 'JSON',
				contentType: "application/JSON; charset=utf-8",
				success: function (result) {
					if (result.status == 200) {
						alert("操作成功!");
						$("#table").bootstrapTable("refresh", {
							silent: true //静态刷新
						});
					}
				},
				error: function () {
					alert('操作失败!');
				},
				complete: function () {
				}
			});
		$('#main1')[0].reset();
		$('#mainId').val('');
		$('.close').click();
	}
});

$("#Audit-repeal").click(function(){
	var rf = confirm("确定撤销此申请吗？");
	var mainId = $("#mainId").val();
    var deleteUrl = DOMAIN + '/v1/ticket' + isLogin + "&id=" + mainId;
    if (rf) {
        $.ajax({
            type: "DELETE",
            url: deleteUrl,
            cache: false,
            async: false,
            success: function (data) {
                alert("撤销成功！");
                if($("#tableApproach")){
                	$("#tableApproach").bootstrapTable("refresh", {
                    silent: true //静态刷新
                });
                }
                $("#table").bootstrapTable("refresh", {
                    silent: true //静态刷新
                });
            }
        });
        $('#main1')[0].reset();
		$('#mainId').val('');
		$('.close').click();
    }
});

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function () {
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions',
		{
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//关闭
$("#AddPur-closeBtn").click(function () {
	$("#close-btn")[0].click();
})

function selectLevelOne(row){
	$("#productLevelOne").val(row.name);
}

function selectLevelTwo(row){
	$("#productLevelTwo").val(row.name);
}

function selectProduct(row){
	$("#productName").val(row.name);
}


